package com.nursing.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.nursing.Dao.ElderDao;
import com.nursing.bean.Elder;
import com.nursing.bean.Nurse;
import com.nursing.model.dto.ElderStatisticsDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class ElderService {
    private  final ElderDao elderDao;

    @Autowired
    public ElderService(ElderDao elderDao) {
        this.elderDao = elderDao;
    }

    public void deleteElder(Integer id) {
        elderDao.delete(id);
    }

    public void updateElder(Elder elder) {
        elderDao.update(elder);
    }

    public void addElder(Elder elder) {
        // 正则校验
        String phone = elder.getPhone();
        if (!phone.matches("1[3-9]\\d{9}")) {
            throw new IllegalArgumentException("手机号格式不正确");
        }
        elder.setCreatedAt(LocalDateTime.now());
        elderDao.insert(elder);
    }

    public PageInfo<Elder> list(int page, int size) {
        PageHelper.startPage(page, size);
        List<Elder> elders = elderDao.getAll();
        return new PageInfo<>(elders);
    }

    public Elder getElderById(Integer id) {
        return elderDao.getById(id);
    }

    public List<ElderStatisticsDto> getMonthlyCount() {
        List<ElderStatisticsDto> dataList = elderDao.getMonthlyCount();
        Map<Integer, Integer> dataMap = new HashMap<>();

        // 先把数据库查询到的数据存入 Map
        for (ElderStatisticsDto dto : dataList) {
            dataMap.put(dto.getMonth(), dto.getCount());
        }

        // 生成 1-12 月的完整数据
        List<ElderStatisticsDto> fullDataList = new ArrayList<>();
        for (int month = 1; month <= 12; month++) {
            fullDataList.add(new ElderStatisticsDto(month, dataMap.getOrDefault(month, 0)));
        }

        return fullDataList;
    }

    public Integer getElderCount() {
        return elderDao.getCount();
    }


}
